package com.learn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.learn.annotation.PassToken;
import com.learn.annotation.UserLoginToken;
import com.learn.pojo.Blog;
import com.learn.pojo.User;
import com.learn.pojo.vo.BlogVo;
import com.learn.service.BlogService;
import com.learn.util.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 描述
 * @author: Mr.Hu
 * @create: 2022/3/20 17:46
 **/
@Controller
public class BlogController {
    @Autowired
    BlogService blogService;
    @RequestMapping("/queryAllBlogs")
    @ResponseBody
    QueryResult<BlogVo> queryAll(){
        return blogService.queryAll();
    }
    @UserLoginToken
    @RequestMapping("/toVue")
    public String toView(){
        return "Vue";
    }

    @RequestMapping("/toDetail/{blogId}")
    public String toDetail(@PathVariable int blogId , Model model) {
        BlogVo blogVo = blogService.queryDetailByBlogId(blogId);
        model.addAttribute("blogVo",blogVo);
        return "detail";
    }
    @UserLoginToken
    @RequestMapping("/toAddBlog")
    public String toAdd(int userId , Model model) {
        model.addAttribute("userId",userId);
        return "add-blog";
    }
    @PassToken
    @RequestMapping("/addBlog")
    public String toAdd( int userId ,String title,String synopsis,String content,int typeId) {
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(userId);
        blog.setTypeId(typeId);
        blog.setSynopsis(synopsis);


        Integer result = blogService.addBlog(blog);
        if (result>0){
            return "main";
        }
        return "add-blog";
    }
    @RequestMapping("/searchByKeyWord")
    public String Login(HttpServletRequest request, @RequestParam("keyword") String keyword,  Model model) {
        BlogVo blogVo = blogService.queryDetailByBlogTitle(keyword);
        if (blogVo == null) {
            String msg = "未找到相关文章";
            model.addAttribute("msg",msg);
            return "searchResult";
        } else {
            List<BlogVo> blogs = new ArrayList<>();
            blogs.add(blogVo);
            model.addAttribute("blogs",blogs);
            return "searchResult";
        }
    }

}
